package utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import swissmap.Constants;

public class DLThread extends Thread {
	private URL u;
	private static int tile=5;
	
	String curres;
	String col, row;

	public DLThread(String curres, int col, int row) {
		
		this.curres = curres;
		this.col = Constants.intoToString(col);
		this.row = Constants.intoToString(row);
		try {
			if(Constants.map){
			u = new URL("http://tile" + tile
					+ ".bgdi.admin.ch/geoadmin/ch.swisstopo.pixelkarte-farbe/"
					+ Constants.res.get(curres) + "/000/000/" + this.col
					+ "/000/000/" + this.row + ".jpeg");
			}else{
				//TODO URL not always correct?!
				u = new URL("http://tile" + tile
						+ ".bgdi.admin.ch/geoadmin/ch.swisstopo.swissimage/"
						+ Constants.res.get(curres) + "/000/000/" + this.col
						+ "/000/000/" + this.row + ".jpeg");
			}
			
			tile++;
			if(tile>9 || tile <5)
				  tile=5;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

	}

	public void run() {
		InputStream is = null;
		try {
			File f = new File(Constants.basePath +"raw"+File.separator+ (Constants.map?"map":"ortho")+File.separator+curres + File.separator
					+ col + File.separator + row + ".jpeg");
			System.out.println(f.getAbsolutePath());
			if (!f.exists()) {
				HttpURLConnection connection = (HttpURLConnection)u.openConnection();
				connection.setRequestProperty("Referer",
						"http://map.geo.admin.ch/?zoom=8&X=190000&Y=660000");

				if(connection.getResponseCode()!=200){
					System.out.println(u.toString());
					System.out.println(connection.getResponseCode()+" "+connection.getResponseMessage());

				}
				

				is = connection.getInputStream();
				
				f.getParentFile().mkdirs();

				OutputStream out = new FileOutputStream(f);
				byte buf[] = new byte[1024];
				int len;
				while ((len = is.read(buf)) > 0)
					out.write(buf, 0, len);
				out.flush();
				out.close();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(is!=null)
					is.close();
			} catch (IOException ioe) {
				// just going to ignore this one
			}
		}
	}
}
